import router from '@/router'
import store from '@/store'
router.beforeEach(async(to, from, next) => {
  const url = to.path
  const token = store.getters.token
  const whiteList = ['/login', '/404']
  // 准备跳转登录页面有token ,跳转到登录页面
  //   (to.path === '/login' && token) && next('/')
  if (token && url === '/login') {
    next('/')
  }
  // 准备跳转登录页面无token ,跳转到登录页面
  //   if (to.path === '/login' && !token) {
  //     next()
  //   }
  if (!token && whiteList.indexOf(url) > -1) {
    next()
  }
  // 准备跳转到白名单有token ,放行
  //   if (whiteList.indexOf(url) === -1 && token) {
  if (token && url !== '/login') {
    if (!store.state.user.userInfo.username) {
      await store.dispatch('user/getUserInfo')
      const routes = await store.dispatch('permission/fiterRouters', store.state.user.userInfo.roles.menus)
      router.addRoutes(
        [
          ...routes,
          { path: '*', redirect: '/404', hidden: true }
        ]
      )
      next(to.path)
    } else {
      next()
    }
  }

  // 准备跳转到白名单无token ,跳转到登录页面
  //   (whiteList.indexOf(url) === -1 && !token) && next('/login')
  if (!token && whiteList.indexOf(url) === -1) {
    next('/login')
  }
})
